/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sda.levelup.lists.arraylist;


import java.util.ArrayList;
import java.lang.IndexOutOfBoundsException;
import sda.levelup.lists.IList;
/**
 *
 * @author Дима
 */
public class ArrayListMine implements IList
{
    private int startSize = 10;
    private Object[] mas = new Object[startSize];
    private int size = 0;
    
    ArrayListMine(){
        
    }
    
    ArrayListMine(int startSize){
        this.startSize = startSize;
        mas = new Object[startSize];
    }

    public int getSize(){
        return size;
    }
    
    public void add(Object o) {
        if (thereAreSpace()) {
            mas[size] = o;
            size++;
        }
        else {
            increaseMas();
            mas[size] = o;
            size++;
        }
    }
    
    public void add(int index, Object o){
        if(isValidIndex(index) && thereAreSpace()){
            System.arraycopy(mas, index, mas, index+1, size-index);
            mas[index]=o;
            size++;
        }
        else if(isValidIndex(index) && !thereAreSpace()){
           increaseMas();
            System.arraycopy(mas, index, mas, index+1, size-index);
            mas[index]=o;
            size++;
        }
        else{
            throw new IndexOutOfBoundsException();
        }
        
    }
    public Object get(int index){
        if(isValidIndex(index)){
            return mas[index];
        }
        else{
            throw new IndexOutOfBoundsException();
        }
    }

    private boolean thereAreSpace() {
        if (size < mas.length) {
            return true;
        }
        else {
            return false;
        }
    }
    private boolean isValidIndex(int ind){
        if(ind>=0 && ind<mas.length){
            return true;
        }
        else{
            return false;
        }
    }

    private void increaseMas() {
        Object[] temp = new Object[mas.length * 3 / 2 + 1];
        System.arraycopy(mas, 0, temp, 0, mas.length);
        mas = temp;
    }
    
    public void remove(int index){
        if(isValidIndex(index)){
            System.arraycopy(mas, index+1, mas, index, size-index-1);
            size--;
        }
        else{
            throw new IndexOutOfBoundsException();
        }
    }
}
